/*
 * File:        playerStatistics.h
 * Authors:     Shaan Mulchandani (ee122-bv) and Jonathan Kotker (ee122-bw)
 * Description: This header file tackles file I/O operations.
 */

#ifndef _FILEIO_H
#define	_FILEIO_H

#include "playerStatistics.h"
#include "constants.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

void srand(unsigned int seed);

void writetofile(playerStatistics* writestats) {
    FILE *fp;

    char fileName[EE122_MAX_NAME_LENGTH + 9];
    memset(fileName, 0, EE122_MAX_NAME_LENGTH);
    strncpy(fileName, "./users/", 8);
    strncpy(fileName + 8, writestats->name, EE122_MAX_NAME_LENGTH);
    fileName[EE122_MAX_NAME_LENGTH + 8] = '\0';

    fp = fopen(fileName, "w+");

    fprintf(fp, "%d ", writestats->hp);
    fprintf(fp, "%d ", writestats->exp);
    fprintf(fp, "%d ", writestats->xLoc);
    fprintf(fp, "%d ", writestats->yLoc);

    fclose(fp);

};

void readfromfile(playerStatistics* readstats) {
    FILE *fp;

    char fileName[EE122_MAX_NAME_LENGTH + 9];
    memset(fileName, 0, EE122_MAX_NAME_LENGTH);
    strncpy(fileName, "./users/", 8);
    strncpy(fileName + 8, readstats->name, EE122_MAX_NAME_LENGTH);
    fileName[EE122_MAX_NAME_LENGTH + 8] = '\0';

    fp = fopen(fileName, "r");
    if (fp == NULL) {
        readstats->hp = (rand() % 20) + 100;
        readstats->exp = 0;
        readstats->xLoc = rand() % 99;
        readstats->yLoc = rand() % 99;
        writetofile(readstats);
    } else {
        fscanf(fp, "%d %d %d %d",
                &(readstats->hp), &(readstats->exp),
                &(readstats->xLoc), &(readstats->yLoc));
        fclose(fp);
    }
};

#endif	/* _FILEIO_H */
